import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:contract_manager/models/contract_model.dart';
import 'package:contract_manager/services/contract_service.dart';
import 'package:contract_manager/pages/contract_list/contract_list_controller.dart';

class ContractEntryController extends GetxController {
  final ContractService _contractService = Get.find();
  final ContractListController _contractListController = Get.find();

  final _formKey = GlobalKey<FormState>();
  final _contractNumberController = TextEditingController();
  final _customerNameController = TextEditingController();
  final _projectNameController = TextEditingController();
  final _contractAmountController = TextEditingController();
  final _paymentTermsController = TextEditingController();
  final _remarksController = TextEditingController();
  DateTime? _contractDate;
  DateTime? _expirationDate;
  String? _contractType;
  String? _paymentMethod;

  void saveContract() async {
    if (_formKey.currentState!.validate() &&
        _contractDate != null &&
        _expirationDate != null) {
      final newId = _contractListController.getMaxId() + 1;

      final contract = Contract(
        newId,
        _contractNumberController.text,
        _customerNameController.text,
        _projectNameController.text,
        _contractDate!,
        _expirationDate!,
        false,
        false,
        double.parse(_contractAmountController.text),
        _contractType!,
        _paymentMethod!,
        _paymentTermsController.text,
        '',
      );

      try {
        await _contractService.batchSaveContracts([contract]);
        Get.back();
        Get.snackbar('成功', '合同已保存');
      } catch (e) {
        Get.snackbar('错误', '保存合同失败: $e');
      }
    } else {
      Get.snackbar('错误', '请填写所有必填项');
    }
  }
}
